package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.SkuEsMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.List

;
import java.util.Map;

@Service
public class SkuServiceImpl implements SkuService {
    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private SkuEsMapper skuEsMapper;

    /**
     * ElasticsearchTemplate 可以实现索引库的增删改查【高级搜索】
     */
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 多条件搜索
     * @param searchMap
     * @return
     */
    @Override
    public Map<String, Object> search(Map<String, String> searchMap) {
        //NativeSearchQueryBuilder 搜索条件的构建对象，用于封装各种搜索条件
        NativeSearchQueryBuilder builder=null;

        /**
         * 执行搜索，响应结果给我
         * 1） 搜索条件封装对象
         * 2） 搜索的结果集（集合数据）需要转换的类型
         *  AggregatedPage<SkuInfo> 搜索结果的封装
         */
        AggregatedPage<SkuInfo> page = elasticsearchTemplate.queryForPage(builder.build(), SkuInfo.class);

        //分页参数，总数记录
        long totalElements = page.getTotalElements();

        //总页数
        int totalPages = page.getTotalPages();

        //获取数据结果集
        List<SkuInfo> contents = page.getContent();

        //封装一个Map存储所有数据，并返回
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("rows",contents);
        resultMap.put("total",totalElements);
        resultMap.put("totalPages",totalPages);

        return resultMap;
    }

    @Override
    public void importData() {
        //调用feign查询数据的所有数据
        Result<List<Sku>> skuResult = skuFeign.findAll();
        //将skuResult 转换为list<skuInfo>
        List<SkuInfo> skuInfos = JSON.parseArray(JSON.toJSONString(skuResult.getData()), SkuInfo.class);

        for (SkuInfo skuInfo : skuInfos) {
            Map<String, Object> specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        //调用skuMapper存入es中
        skuEsMapper.saveAll(skuInfos);
    }
}